package com.digitalchina.lxnsy.activity.management;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.LoginGuideActivity;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.EntAuthVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.SharedPreferencesUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

public class EnterpriseAuthActivity extends BaseActivity {

    @Bind(R.id.et_name)
    EditTextWithClear etName;
    @Bind(R.id.et_contact)
    EditTextWithClear etContact;
    @Bind(R.id.et_address)
    EditTextWithClear etAddress;
    @Bind(R.id.et_personalProfile)
    EditTextWithClear etPersonalProfile;
    @Bind(R.id.et_businessScope)
    EditTextWithClear etBusinessScope;
    @Bind(R.id.et_socialCreditCode)
    EditTextWithClear etSocialCreditCode;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;
    @Bind(R.id.tv_area)
    TextView tvArea;

    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.tv_audit)
    TextView tvAudit;
    @Bind(R.id.tv_auditOpinion)
    TextView tvAuditOpinion;
    @Bind(R.id.tv_auditTime)
    TextView tvAuditTime;
    @Bind(R.id.layout_audit)
    LinearLayout layoutAudit;

    //标记地址控件是否可以显示
    boolean areaEdit = true;

    private int select = 0;
    //已上传图片数组
    private String[] imgs = {"", "", "", ""};
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[imgs.length];
    public static final int REQUEST_CODE_SELECT = 100;
    /**
     * userAccId	T文本	是
     * 用户id
     * <p>
     * name	T文本	是
     * 单位名称
     * <p>
     * contactName	T文本	是
     * 联系人
     * <p>
     * provinceCode	T文本	是
     * 省code
     * <p>
     * cityCode	T文本	否
     * 市code
     * <p>
     * countyCode	T文本	否
     * 区code
     * <p>
     * address	T文本	否
     * 详细地址
     * <p>
     * personalProfile	T文本	否
     * 单位简介
     * <p>
     * businessScope	T文本	否
     * 经营范围
     * <p>
     * socialCreditCode	T文本	是
     * 社会信用统一代码
     * <p>
     * businessLicenseImgs[0]	T文本	是
     * 营业执照图片列表
     */

    private String name, contactName, provinceCode, cityCode, countyCode, address, personalProfile, businessScope, socialCreditCode, businessLicenseImgs;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_enterprise_auth);
        setTitle("企业认证");

        setRightText("退出");
        hideBackBtn();
    }

    @Override
    public void initMember() {

        //是否审核通过 0 审核未通过  1 审核通过  2 待审核  3 已注册 未提交
        if (!"3".equals(AdminXML.getIsAudit(activity))) {
            queryCertificateInfo();
        }

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）

        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;


    }

    // 获取企业认证信息
    private void queryCertificateInfo() {
        HttpParams params = new HttpParams();
        params.put("userAccId", UserXML.getUserId(activity));

        OkHttpUtil.post(activity, URL.URL_QUERYCERTIFICATEINFO, "正在获取数据...", params, mHandler,
                MSG_S_1, MSG_F_1);
    }


    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_S_0: // 成功
                        showToast("提交成功");
                        disableView();
//                        queryCertificateInfo();
                        break;
                    case MSG_F_0: // 失败
                    case MSG_F_1:
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                    case MSG_S_1: // 获取认证信息
                        setView(msg.obj);
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            imgs[select] = fileVO.getName();
                            FrescoUtil.showImageSmall(imgs[select], sdvArray[select]);
                        }
                        break;
                }
                return false;
            }
        });
    }

    //回填数据
    private void setView(Object obj) {
        EntAuthVO vo = FastJsonUtil.getBean(obj.toString(), EntAuthVO.class);
        if (vo != null) {

            AdminXML.setIsAudit(activity, vo.getIsAudit());

            switch (vo.getIsAudit()) {
                case "0":
                    //审核未通过
                    layoutAudit.setVisibility(View.VISIBLE);
                    tvAuditOpinion.setVisibility(View.VISIBLE);
                    tvAudit.setText("审核状态：审核未通过");
                    tvAuditOpinion.setText("审核意见："+vo.getAuditOpinion());
                    tvAuditTime.setText("审核时间："+vo.getAuditTime());
                    break;
                case "1":
                    //审核通过
                    GotoUtil.gotoActivity(activity, ManagementDetailsV2Activity.class);
                    ActivityTaskManager.getInstance().closeAllActivityExceptOne(ManagementDetailsV2Activity.class);
                    break;
                case "2":
                    //待审核
                    disableView();
                    layoutAudit.setVisibility(View.VISIBLE);
                    tvAudit.setText("审核状态：待审核");
                    tvAuditTime.setText("提交时间："+vo.getCertificateSubmitTime());
                    break;
            }

            etName.setText(vo.getName());
            etContact.setText(vo.getContactName());
            etAddress.setText(vo.getAddress());
            etPersonalProfile.setText(vo.getPersonalProfile());
            etBusinessScope.setText(vo.getBusinessScope());
            etSocialCreditCode.setText(vo.getSocialCreditCode());

            String area = "";
            if (vo.getProvince() != null) {
                area += vo.getProvince().getProvinceName();
                provinceCode = vo.getProvince().getProvinceCode();
            }
            if (vo.getCity() != null) {
                area += vo.getCity().getCityName();
                cityCode = vo.getCity().getCityCode();
            }
            if (vo.getCounty() != null) {
                area += vo.getCounty().getCountyName();
                countyCode = vo.getCounty().getCountyCode();
            }
            tvArea.setText(area);

            for (SimpleDraweeView simpleDraweeView : sdvArray) {
                simpleDraweeView.setVisibility(View.INVISIBLE);
            }
            if (vo.getBusinessLicenseImgs() != null) {
                for (int i = 0; i < vo.getBusinessLicenseImgs().size(); i++) {
                    imgs[i] = vo.getBusinessLicenseImgs().get(i).getPictureVideoId();
                    FrescoUtil.showImageSmall(imgs[i], sdvArray[i]);
                    sdvArray[i].setVisibility(View.VISIBLE);
                }
            }

        }

    }

    //展示数据 禁止编辑
    private void disableView() {
        etName.setEnabled(false);
        etContact.setEnabled(false);
        etAddress.setEnabled(false);
        etPersonalProfile.setEnabled(false);
        etBusinessScope.setEnabled(false);
        etSocialCreditCode.setEnabled(false);

        areaEdit = false;
        btnSubmit.setVisibility(View.GONE);

        for (int i = 0; i < sdvArray.length; i++) {
            if (!StringUtil.isStrEmpty(imgs[i])) {
                FrescoUtil.showImageSmall(imgs[i], sdvArray[i]);
            }else{
                sdvArray[i].setVisibility(View.GONE);
            }
        }
    }


    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {
        new MaterialDialog.Builder(activity)
                .title("提示")
                .content("您确定要退出登录吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        SharedPreferencesUtil.cleanXml(activity, AdminXML.NAME);
                        go(LoginGuideActivity.class);
                        ActivityTaskManager.getInstance().closeAllActivity();
                    }
                })
                .show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.sdv_img0, R.id.sdv_img1, R.id.sdv_img2, R.id.sdv_img3, R.id.rl_area, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_area:
                if (areaEdit)
                    showAddress();
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.sdv_img1:
                selectImage(1);
                break;
            case R.id.sdv_img2:
                selectImage(2);
                break;
            case R.id.sdv_img3:
                selectImage(3);
                break;
        }
    }

    // 选择图片
    private void selectImage(int i) {
        if (areaEdit){
            select = i;
            if (StringUtil.isStrEmpty(imgs[select])) {
                Intent intent = new Intent(activity, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
            } else {
                new MaterialDialog.Builder(activity)
                        .title("提示")
                        .content("是否删除这张照片？")
                        .positiveText("删除")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                imgs[select] = "";
                                Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);
                                sdvArray[select].setImageURI(uri);
                            }
                        })
                        .show();
            }
        }
    }

    /**
     * 跳转回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        }

    }

    private void showAddress() {
        final BottomDialog bottomDialog = new BottomDialog(activity);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                String provinceName = province.province_name;
                String cityName = city != null ? city.city_name : "";
                String countyName = county != null ? county.county_name : "";

                provinceCode = province.province_code;
                cityCode = city != null ? city.city_code : "";
                countyCode = county != null ? county.county_code : "";

                tvArea.setText(String.format("%s %s %s", provinceName, cityName
                        , countyName));
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    //提交
    private void submit() {
        name = etName.getText().toString();
        if (StringUtil.isStrEmpty(name)) {
            showToast("请输入单位名称");
            return;
        }
        contactName = etContact.getText().toString();
        if (StringUtil.isStrEmpty(contactName)) {
            showToast("请输入联系人");
            return;
        }

        if (StringUtil.isStrEmpty(provinceCode)) {
            showToast("请先择所属区域");
            return;
        }
        socialCreditCode = etSocialCreditCode.getText().toString();
        if (StringUtil.isStrEmpty(socialCreditCode)) {
            showToast("请输入社会信用统一代码");
            return;
        }


        HttpParams params = new HttpParams();
        params.put("userAccId", UserXML.getUserId(activity));
        params.put("name", name);
        params.put("contactName", contactName);
        params.put("provinceCode", provinceCode);
        params.put("cityCode", cityCode);
        params.put("countyCode", countyCode);
        params.put("socialCreditCode", socialCreditCode);


        address = etAddress.getText().toString();
        personalProfile = etPersonalProfile.getText().toString();
        businessScope = etBusinessScope.getText().toString();

        params.put("address", address);
        params.put("personalProfile", personalProfile);
        params.put("businessScope", businessScope);

        //图片
        boolean emptyArr = true;
        for (int i = 0; i < imgs.length; i++) {
            if (!StringUtil.isStrEmpty(imgs[i])) {
                params.put("businessLicenseImgs[" + i + "]", imgs[i]);
                emptyArr = false;
            }
        }

        if (emptyArr) {
            showToast("请上传资质图片");
            return;
        }

        OkHttpUtil.post(activity, URL.URL_ENTERPRISECERTIFICATE, "正在提交", params, mHandler,
                MSG_S_0, MSG_F_0);
    }
}
